# encoding=utf-8
import os
import traceback
from seg_system.Multibatch.service.SaveService import SaveService
from seg_system.Vascular.service.VascularDirFactory import VascularDirFactory


class FileCleanService:
    """FileCleanService:
        - 客户需要删除上传事失误的图像，对应界面操作的删除
    """

    def clean_main(self, img_name: str, seg_saver, vascular_saver):
        img_path, txt_path = self.make_clean_path(seg_saver, vascular_saver, img_name)
        self.file_delete(img_path + txt_path)
        return {'code': 200, 'result': 'success'}

    def file_delete(self, file_path_list):
        for each_file in file_path_list:
            self.try_delete(each_file)

    def try_delete(self, name):
        if os.path.exists(name):
            try:
                os.remove(name)
            except:
                print(traceback.format_exc())

    def make_clean_path(self, seg_saver, vascular_saver, img_name: str):
        i1, t1 = self.make_seg_clean_path(seg_saver, img_name)
        i2, t2 = self.make_vascular_clean_path(vascular_saver, img_name)

        return i1 + i2, t1 + t2

    def make_seg_clean_path(self, seg_saver: SaveService, img_name: str):
        i1 = [seg_saver.NORMAL_0, seg_saver.NORMAL_1, seg_saver.NORMAL_1_1,
              seg_saver.NORMAL_2, seg_saver.NORMAL_3, seg_saver.NORMAL_TMP,
              seg_saver.ENHANCE_0, seg_saver.ENHANCE_1, seg_saver.ENHANCE_1_1,
              seg_saver.ENHANCE_2, seg_saver.ENHANCE_3, seg_saver.ENHANCE_TMP]
        i2 = [seg_saver.NORMAL_2_1, seg_saver.ENHANCE_2_1]
        return [os.path.join(i, img_name) for i in i1], [os.path.join(i, img_name + '.txt') for i in i2]

    def make_vascular_clean_path(self, vascular_saver: VascularDirFactory, img_name: str):
        i1 = [vascular_saver.NORMAL_0, vascular_saver.NORMAL_1, vascular_saver.NORMAL_1_0,
              vascular_saver.NORMAL_1_1, vascular_saver.ENHANCE_0, vascular_saver.ENHANCE_1,
              vascular_saver.ENHANCE_1_0, vascular_saver.ENHANCE_1_1]
        i2 = [vascular_saver.NORMAL_2, vascular_saver.NORMAL_3, vascular_saver.ENHANCE_2,
              vascular_saver.ENHANCE_3]
        return [os.path.join(i, img_name) for i in i1], [os.path.join(i, img_name + '.txt') for i in i2]
